package com.mediacloud.app.newsmodule.fragment.ugc

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mediacloud.app.fbnavsk.initFStyle
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.fragment.ugc.mod.CmsCatalogListResult
import com.mediacloud.app.newsmodule.utils.*
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.RxUtils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.fragment_liteav_home_list.*


class LiteAvHomeFragment : HqyNavFragment(), DataInvokeCallBack<ArticleListData>, OnRefreshLoadMoreListener {
    private lateinit var dataInvoker: NewsListDataInvoker
    private lateinit var componentAdapter: BaseComponentAdapter<ComponentItem>
    private lateinit var contentAdapter: LiteAvListAdapter2
    private var page: Int = 1
    private var perPage = 15
    private var catalogID: String? = null
    private var catalogItem: CatalogItem? = null
    var contentListCache = ContentListCache<Any>(null)
    override fun getLayoutResID(): Int {
        return R.layout.fragment_liteav_home_list
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (hadChoosed) {
            initFStyle(mRefreshLayout, null)
        } else {
            navPaddingTopMatch()
        }
    }

    override fun initView() {

        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = fragmentArguments.getString("id")
            catalogItem = fragmentArguments.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        }
        loadingView = findViewById(R.id.mLoadingView)
        contentListCache.pageSize = perPage
        contentListCache.catalogId = catalogID!!
        mRefreshLayout.setOnRefreshLoadMoreListener(this)

        mRecyclerView1.layoutManager = LinearLayoutManager(requireContext())
        componentAdapter = BaseComponentAdapter(requireContext())
        componentAdapter.catalogItem = catalogItem
        mRecyclerView1.adapter = componentAdapter

        contentAdapter = LiteAvListAdapter2(requireContext())
        contentAdapter.navigateId = "$catalogID"
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        //  layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        mRecyclerView2.layoutManager = layoutManager
        mRecyclerView2.addItemDecoration(GridItemDecoration(2, requireContext().resources.getDimensionPixelSize(R.dimen.dimen10), false))

        mRecyclerView2.adapter = contentAdapter
        dataInvoker = NewsListDataInvoker(this)
        getCmsCatalogList()
        contentListCache.clear()
        showStateView(TYPE_LOADING,false)
        val dataResult = this.readData("$catalogID", ArticleListData::class.java)
        if (dataResult != null && dataResult.articleList.size > 0) {
            success(dataResult)
        } else {
            getData()
        }
    }

    private fun getData() {

        dataInvoker.getContentListWithAd("$catalogID", page, perPage,null)
    }


    @SuppressLint("CheckResult")
    private fun getCmsCatalogList() {

        DataInvokeUtil.getZiMeiTiApi().getCmsCatalogList(31)
                .compose(TransUtils.fastJSonTransform(CmsCatalogListResult::class.java))
                .compose(RxUtils.schedulersTransformer())
                .subscribe {
                    if (it.data.meta.isNotEmpty()) {
                        it.data.meta.removeAt(0)
                    }
                    hotView.setCmsCatalogList(it.data.meta)
                }
    }

    override fun success(data: ArticleListData?) {
        mRefreshLayout.setEnableRefresh(true)
        mRefreshLayout.setEnableLoadMore(true)
        mRefreshLayout.finishRefresh()
        mRefreshLayout.finishLoadMore(true)
        data?.let {
            if (page == 1) {
                saveData("$catalogID", it.orginData.toString() + "")
                componentAdapter.setDate(it.componentItems)
                contentAdapter.data.clear()
                val data = it.orginData.optJSONObject("data")
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data)
                } else {
                    hideFloatWin()
                }
            }
            contentAdapter.pageIndex = page
            contentAdapter.addData(it.articleList)
            mRefreshLayout.setNoMoreData(!it.haveMore())
            closeStateView()
//            if (page == 1) {
//                if (it.articleList.isEmpty() && it.componentItems.isEmpty() && hotView.adapter.data.size == 0) {
//                    showStateView(TYPE_NO_CONTENT, false)
//                } else {
//                    closeStateView()
//                }
//            } else {
//                closeStateView()
//
//            }
            contentListCache.pageNum = perPage + 1
            contentListCache.preload2()
        }

    }

    override fun fault(data: Any?) {
        mRefreshLayout.setEnableRefresh(true)
        mRefreshLayout.setEnableLoadMore(true)
        mRefreshLayout.finishRefresh()
        mRefreshLayout.finishLoadMore(true)
        showStateView(TYPE_NO_CONTENT, false)

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
//        mRefreshLayout.setEnableRefresh(false)
//        mRefreshLayout.setEnableLoadMore(false)
        getCmsCatalogList()
        page = 1
        contentListCache.clear()
        getData()
    }


    override fun onLoadMore(refreshLayout: RefreshLayout) {
//        mRefreshLayout.setEnableRefresh(false)
//        mRefreshLayout.setEnableLoadMore(false)
        page++
        getData()
    }

    override fun onDestroyView() {
        if (componentAdapter != null) {
            componentAdapter.destroy()
        }
        super.onDestroyView()
    }
}